﻿namespace Tszy.Unlimited.Base.Infrastructure.Events;

/// <summary>
/// 事件监听器。
/// </summary>
public interface IEventListener
{
    /// <summary>
    /// 事件类型。
    /// </summary>
    Type EventType { get; }

    /// <summary>
    /// 监听事件。
    /// </summary>
    /// <param name="sender">事件发送者。</param>
    /// <param name="event">事件信息。</param>
    void Listen(object? sender, object @event);
}

/// <summary>
/// 事件监听器。
/// </summary>
/// <typeparam name="TEvent">事件类型。</typeparam>
public interface IEventListener<TEvent> : IEventListener where TEvent : notnull
{
    /// <summary>
    /// 监听事件。
    /// </summary>
    /// <param name="sender">事件发送者。</param>
    /// <param name="event">事件信息。</param>
    void Listen(object? sender, TEvent @event);
}

/// <summary>
/// 事件监听器。
/// </summary>
/// <typeparam name="TEvent">事件类型。</typeparam>
public abstract class EventListener<TEvent> : IEventListener<TEvent> where TEvent : notnull
{
    /// <summary>
    /// 事件类型。
    /// </summary>
    public Type EventType => typeof(TEvent);

    /// <summary>
    /// 监听事件。
    /// </summary>
    /// <param name="sender">事件发送者。</param>
    /// <param name="event">事件信息。</param>
    public void Listen(object? sender, TEvent @event)
    {
        OnListen(sender, @event);
    }

    /// <summary>
    /// 监听事件。
    /// </summary>
    /// <param name="sender">事件发送者。</param>
    /// <param name="event">事件信息。</param>
    public void Listen(object? sender, object @event)
    {
        OnListen(sender, (TEvent)@event);
    }

    /// <summary>
    /// 监听事件。
    /// </summary>
    /// <param name="sender">事件发送者。</param>
    /// <param name="event">事件信息。</param>
    protected abstract void OnListen(object? sender, TEvent @event);
}
